﻿
namespace EasyNet.Solr.Impl
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Xml.Linq;

    /// <summary>
    /// xml格式返回数据高亮解析器
    /// </summary>
    public class XmlHighlightingParser : ISolrResponseParser<string, IDictionary<string, IDictionary<string, IList<string>>>>
    {
        public IDictionary<string, IDictionary<string, IList<string>>> Parse(string result)
        {
            if (string.IsNullOrEmpty(result))
            {
                return null;
            }

            var xmlDoc = XDocument.Parse(result);

            var highlighting = from e in xmlDoc.Root.Elements("lst")
                               where (string)e.Attribute("name") == "highlighting"
                               select e;

            if (highlighting == null)
            {
                return null;
            }

            var hlResult = from e in highlighting.Elements("lst")
                           select e;
            var highlightingResult = new Dictionary<string, IDictionary<string, IList<string>>>(hlResult.Count());

            foreach (XElement hlElement in hlResult)
            {
                var itemName = hlElement.Attribute("name").Value;
                var itemList = from e in hlElement.Elements("arr")
                               select e;

                if (!highlightingResult.ContainsKey(itemName))
                {
                    highlightingResult[itemName] = new Dictionary<string, IList<string>>(itemList.Count());
                }

                foreach (var itemElement in itemList)
                {
                    var hlItemName = itemElement.Attribute("name").Value;

                    if (!highlightingResult[itemName].ContainsKey(hlItemName))
                    {
                        highlightingResult[itemName][hlItemName] = new List<string>();
                    }

                    highlightingResult[itemName][hlItemName] = (from e in itemElement.Elements("str")
                                                                select e.Value).ToList<string>();
                }
            }

            return highlightingResult;

        }
    }
}
